<template>
  <div v-loading="loading" class="health-records-detail common-page">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="bg-white sticky top-0 z-10">
        <div class="flex items-center py-3">
          <el-button :icon="ArrowLeft" text class="!p-2 mr-2" @click="goBack" />
          <span class="text-lg font-medium">{{
            t("healthRecords.detail.title")
          }}</span>
        </div>
      </div>
      <div class="modify-btn">
        <el-button type="primary" text @click="showRecordPage">{{
          t("healthRecords.detail.modifyRecord")
        }}</el-button>
      </div>
    </div>
    <!-- 家庭成员切换tab -->
    <div v-if="isFamilyMode" class="family-tabs-container mb-4">
      <div class="family-member-tabs">
        <div
          v-for="member in familyMembers"
          :key="member.userId"
          :class="[
            'family-member-tab',
            { active: activeFamilyMember === String(member.userId) }
          ]"
          @click="handleFamilyMemberChange(String(member.userId))"
        >
          {{
            member.displayName ||
            t("healthRecords.detail.memberLabel", { userId: member.userId })
          }}
        </div>
      </div>
    </div>
    <!-- 报告信息卡片 -->
    <div v-if="!isFamilyMode">
      <div class="!border-blue-400 border p-1 !bg-blue-100 min-w-full">
        <div class="text-gray-600 text-sm flex max-w-3/4">
          <div>{{ archiveDetail?.userName }}</div>
          <div class="ml-8">{{ archiveDetail?.updateDate }}</div>
        </div>
      </div>
    </div>

    <!-- 健康画像和指数区域 -->
    <div class="health-overview">
      <!-- 左侧：全局健康画像 -->
      <div class="health-portrait">
        <div class="portrait-header">
          <div class="flex items-center">
            <div class="w-1 h-5 bg-blue-400 rounded-2xl mr-4" />
            <span class="font-medium">{{
              t("healthRecords.detail.globalHealthProfile")
            }}</span>
          </div>
          <p>{{ t("healthRecords.detail.healthIndexDescription") }}</p>
        </div>
        <div class="portrait-body">
          <div class="tag tag-subhealth">
            {{ archiveDetail?.healthCategory }}
          </div>
          <div class="tag-info">
            <div class="tag tag-status">
              {{
                t("healthRecords.detail.healthIndexLabel", {
                  value: archiveDetail?.phi || 0
                })
              }}
            </div>
            <el-icon class="info-icon"><InfoFilled /></el-icon>
          </div>

          <!-- 健康指数卡片 -->
          <div class="health-card">
            <div class="card-title">
              {{ t("healthRecords.detail.healthIndexTitle") }}
            </div>
            <!-- 圆形进度条 -->
            <HealthIndexCircle
              :health-score="Number(archiveDetail?.phi || 0)"
            />
          </div>
        </div>

        <!-- 人体模型区域 -->
        <!-- 人体模型区域 -->
        <div class="model-image">
          <img
            v-if="archiveDetail?.archiveBasicInfo?.gender == '1'"
            src="@/assets/images/healthRecords/body-model-man.png"
            alt="男性人体模型"
          />
          <img
            v-else
            src="@/assets/images/healthRecords/body-model-woman.png"
            alt="女性人体模型"
          />
        </div>
      </div>

      <!-- 右侧：健康指数图表 -->
      <div class="health-chart">
        <div class="chart-header">
          <h3>{{ t("healthRecords.detail.healthIndexChart") }}</h3>
        </div>
        <div class="chart-container">
          <!-- 这里放置ECharts图表组件 -->
          <div ref="chartRef" class="chart" />
        </div>
      </div>
    </div>

    <!-- 标签页区域 -->
    <el-card>
      <el-tabs v-model="activeTab" class="health-tabs">
        <el-tab-pane :label="t('healthRecords.detail.tabs.basic')" name="basic">
          <BasicInfoComponent
            v-if="activeTab === 'basic'"
            requestSource="1"
            :archive-info="archiveDetail?.archiveBasicInfo"
            @update-success="fetchArchiveDetail"
          />
        </el-tab-pane>

        <el-tab-pane
          :label="t('healthRecords.detail.tabs.health')"
          name="health"
        >
          <HealthInfoComponent
            v-if="activeTab === 'health'"
            :requestSource="1"
            :archive-info="archiveDetail?.archiveHealthInfo"
            @update-success="fetchArchiveDetail"
          />
        </el-tab-pane>

        <el-tab-pane
          :label="t('healthRecords.detail.tabs.lifestyle')"
          name="lifestyle"
        >
          <LifestyleComponent
            v-if="activeTab === 'lifestyle'"
            :requestSource="1"
            :archive-info="archiveDetail?.archiveLifestyleInfo"
            @update-success="fetchArchiveDetail"
          />
        </el-tab-pane>

        <el-tab-pane :label="t('healthRecords.detail.tabs.risk')" name="risk">
          <RiskAssessmentComponent
            v-if="activeTab === 'risk'"
            :reportId="String(archiveDetail.archiveId)"
            :reportType="2"
            requestSource="1"
          />
        </el-tab-pane>
        <el-tab-pane
          :label="t('healthRecords.detail.tabs.advice')"
          name="advice"
        >
          <AdviceComponent
            v-if="activeTab === 'advice'"
            :reportId="String(archiveDetail.archiveId)"
            :reportType="2"
            :requestSource="1"
          />
        </el-tab-pane>
        <el-tab-pane :label="'风险等级'" name="riskLevel">
          <el-form-item label="风险等级" class="w-1/4">
            <el-select
              v-model="riskLevel"
              :disabled="!isEditing"
              placeholder="请选择风险等级"
            >
              <el-option
                v-for="item in dictData.riskLevelList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <div class="flex justify-end mt-20">
            <el-button @click="handleEditRiskLevel"> 编辑 </el-button>
            <el-button type="primary" @click="handleSaveLevel(1)">
              保存
            </el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="'健康分类'" name="healthCategory">
          <el-form-item label="健康分类" class="w-1/4">
            <el-select
              v-model="healthCategory"
              :disabled="!isEditing"
              placeholder="请选择健康分类"
            >
              <el-option
                v-for="item in dictData.healthCategoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <div class="flex justify-end mt-20">
            <el-button @click="handleEditRiskLevel"> 编辑 </el-button>
            <el-button type="primary" @click="handleSaveLevel(2)">
              保存
            </el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="'健康标签'" name="healthLabel">
          <!-- 健康标签组件 -->
          <HealthLabel
            v-if="activeTab === 'healthLabel'"
            v-model="showHealthLabelDrawer"
            :report-id="archiveDetail.archiveId.toString()"
            :report-type="1"
            mode="normal"
            title="健康标签"
            @submit-success="fetchArchiveDetail"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 修改记录抽屉 -->
    <record-page ref="recordPageRef" :list="recordList" />
  </div>
</template>

<script setup lang="ts">
import { healthApi } from "@/api/health";
import type { HealthArchiveDetailData } from "@/api/types";
import type { FamilyInfoVO } from "@/api/types/user";
import { getFamilyInfo } from "@/api/user";
import { useToolsStore } from "@/store/modules/tools";
import RecordPage from "@/views/components/recordPage.vue";
import { ArrowLeft, InfoFilled } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";

const toolsStore = useToolsStore();
// 导入子组件（需要创建这些组件）
import HealthLabel from "@/views/report/components/healthLabel/index.vue";
import AdviceComponent from "./advice.vue";
import BasicInfoComponent from "./components/BasicInfo.vue";
import HealthInfoComponent from "./components/HealthInfo.vue";
import LifestyleComponent from "./components/WayOfLife.vue";
import HealthIndexCircle from "./HealthIndexCircle.vue";
import RiskAssessmentComponent from "./riskAssessment.vue";

const dictData = computed(() => toolsStore.getDictData());

const riskLevel = ref("");
const isEditing = ref(false);
const healthCategory = ref("");
const showHealthLabelDrawer = ref(true);
const handleEditRiskLevel = () => {
  isEditing.value = true;
};
const handleSaveLevel = async (type: number) => {
  const res = await healthApi.getHealthArchiveUpdateHealthCategory({
    dateType: type,
    dataId: type === 1 ? riskLevel.value : healthCategory.value,
    userId: route.query.userId
  });

  if (res.code === 0) {
    fetchArchiveDetail();
    isEditing.value = false;
  }
};
console.log("dictData", dictData.value);
// riskLevelList
const router = useRouter();
const route = useRoute();

// 国际化
const { t } = useI18n();
const activeTab = ref("basic");
const chartRef = ref();
const loading = ref(false);
const archiveDetail = ref<HealthArchiveDetailData | null>(null);

// 家庭成员相关状态
const familyMembers = ref<FamilyInfoVO[]>([]);
const activeFamilyMember = ref<string>("");
const isFamilyMode = computed(() => !!route.query.familyId);
// 计算当前reportId
const currentReportId = computed(() => {
  if (isFamilyMode.value) {
    // 家庭模式下，使用当前选中成员的userId作为reportId
    return activeFamilyMember.value || route.query.userId;
  } else {
    // 个人模式下，使用archiveDetail中的archiveId
    return archiveDetail.value?.archiveId || route.query.userId;
  }
});

// 获取家庭成员信息
const fetchFamilyInfo = async () => {
  if (!isFamilyMode.value) return;

  try {
    const familyId = Number(route.query.familyId);
    if (!familyId) {
      ElMessage.error(t("healthRecords.detail.messages.missingFamilyId"));
      return;
    }

    const response = await getFamilyInfo({ familyId });
    if (response?.data) {
      familyMembers.value = Array.isArray(response.data)
        ? response.data
        : [response.data];

      // 设置默认选中的家庭成员
      if (familyMembers.value.length > 0) {
        const defaultUserId =
          route.query.userId || familyMembers.value[0].userId;
        activeFamilyMember.value = String(defaultUserId);
      }
    }
  } catch (error) {
    console.error("获取家庭信息失败:", error);
    ElMessage.error(t("healthRecords.detail.messages.fetchFamilyInfoFailed"));
  }
};

// 处理家庭成员切换
const handleFamilyMemberChange = (userId: string) => {
  activeFamilyMember.value = userId;
  fetchArchiveDetail(Number(userId));
};

// 获取健康档案详情
const fetchArchiveDetail = async (userId?: number) => {
  try {
    loading.value = true;
    // 确定要查询的userId
    let targetUserId: number;
    if (userId) {
      targetUserId = userId;
    } else if (isFamilyMode.value && activeFamilyMember.value) {
      targetUserId = Number(activeFamilyMember.value);
    } else {
      targetUserId = Number(route.query.userId);
    }

    const response = await healthApi.getDetail({ userId: targetUserId });

    if (response.code === 0) {
      archiveDetail.value = response.data;
      archiveDetail.value.archiveBasicInfo.userName = response.data.userName;
      riskLevel.value = response.data.riskLevelId || "";
      healthCategory.value = response.data.healthCategoryId || "";
      console.log("健康档案详情:", archiveDetail.value);
      // 重新初始化图表
      nextTick(() => {
        initChart();
      });
    } else {
      ElMessage.error(
        response.message || t("healthRecords.detail.messages.fetchDetailFailed")
      );
    }
  } catch (error) {
    console.error("获取健康档案详情失败:", error);
    ElMessage.error(t("healthRecords.detail.messages.fetchDetailFailedRetry"));
  } finally {
    loading.value = false;
  }
};
// 修改记录相关
const recordPageRef = ref();
const recordList = ref([]);

// 显示修改记录
const showRecordPage = () => {
  // 这里可以添加获取修改记录的接口调用
  recordPageRef.value?.open({
    dataId: archiveDetail.value?.archiveId,
    type: 6
  });
};
const initChart = () => {
  nextTick(() => {
    if (!chartRef.value) return;

    const chart = echarts.init(chartRef.value);

    // 处理真实数据或使用默认数据
    let chartData = [];
    let timeLabels = [];

    if (
      archiveDetail.value?.archiveEvaluations &&
      archiveDetail.value.archiveEvaluations.length > 0
    ) {
      // 使用真实数据 - 直接使用 time 字段，因为已经是年-月-日格式
      const evaluations = archiveDetail.value.archiveEvaluations;
      timeLabels = evaluations.map(item => item.time);
      chartData = evaluations.map(item => item.result);
    } else {
      // 使用默认数据
      timeLabels = [
        "2024-01-01",
        "2024-01-02",
        "2024-01-03",
        "2024-01-04",
        "2024-01-05",
        "2024-01-06",
        "2024-01-07"
      ];
      chartData = [30, 35, 40, 45, 50, 55, 60];
    }

    const option = {
      title: {
        text: t("healthRecords.detail.healthIndexTrend"),
        left: "center",
        textStyle: {
          fontSize: 16,
          color: "#333"
        }
      },
      tooltip: {
        trigger: "axis",
        formatter: function (params) {
          const data = params[0];
          // 将i18n文本中的换行符替换为HTML换行标签，用于ECharts tooltip显示
          return t("healthRecords.detail.chartTooltip", {
            time: data.name,
            value: data.value
          }).replace(/\n/g, "<br/>");
        }
      },
      grid: {
        left: "10%",
        right: "10%",
        bottom: "15%",
        top: "20%"
      },
      xAxis: {
        type: "category",
        data: timeLabels,
        axisLabel: {
          color: "#666",
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: "#e0e0e0"
          }
        }
      },
      yAxis: {
        type: "value",
        name: t("healthRecords.detail.healthIndexChart"),
        nameTextStyle: {
          color: "#666"
        },
        axisLabel: {
          color: "#666",
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: "#e0e0e0"
          }
        },
        splitLine: {
          lineStyle: {
            color: "#f0f0f0"
          }
        }
      },
      series: [
        {
          name: t("healthRecords.detail.healthIndexChart"),
          data: chartData,
          type: "line",
          smooth: true,
          symbol: "circle",
          symbolSize: 6,
          lineStyle: {
            color: "#4285f4",
            width: 3
          },
          itemStyle: {
            color: "#4285f4"
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "rgba(66, 133, 244, 0.3)"
                },
                {
                  offset: 1,
                  color: "rgba(66, 133, 244, 0.05)"
                }
              ]
            }
          }
        }
      ]
    };

    chart.setOption(option);

    // 响应式调整图表大小
    const resizeHandler = () => {
      chart.resize();
    };

    window.addEventListener("resize", resizeHandler);

    // 组件卸载时移除事件监听
    onUnmounted(() => {
      window.removeEventListener("resize", resizeHandler);
      chart.dispose();
    });
  });
};
const goBack = () => {
  router.back();
};

onMounted(async () => {
  if (isFamilyMode.value) {
    await fetchFamilyInfo();
  }
  await fetchArchiveDetail();
});
</script>

<style scoped>
/* 顶部导航 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
}

.modify-btn {
  color: #409eff;
}

/* 健康画像和指数区域 */
.health-overview {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  margin-top: 24px;
  height: 500px;
}

.health-portrait {
  flex: 1;
  border-radius: 12px;
  padding: 20px;
  background-image: url("@/assets/images/healthRecords/body-model-bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

.portrait-header h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #333;
}

.portrait-header p {
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.4);
  margin-left: 19px;
}

.model-image {
  position: absolute;
  right: 31px;
  bottom: 20px;
}

.model-image img {
  width: 152px;
  height: 432px;
}
.portrait-body {
  .tag {
    padding: 2px 8px;
    font-weight: 500;
    font-size: 14px;
    color: #222222;
    line-height: 16px;
    margin: 25px 0;
  }
  .tag-info {
    display: flex;
    align-items: center;
  }
  .tag-subhealth {
    background: #95fbf4;
    border-radius: 4px;
    border: 1px solid #ffffff;
    width: fit-content;
  }
  .tag-status {
    background: linear-gradient(138deg, #6effb9 0%, #6fff7f 100%);
    border-radius: 4px;
    border: 1px solid #ffffff;
    width: fit-content;
  }
  /* 健康指数卡片 */
  .health-card {
    width: fit-content;
    padding: 10px;
    background: rgba(255, 255, 255, 0.56);
    box-shadow:
      0px 1px 16px 0px rgba(0, 212, 229, 0.24),
      inset 1px 1px 1px 0px #ffffff;
    border-radius: 16px;
    border: 1px solid #ffffff;
    backdrop-filter: blur(1px);
    .card-title {
      font-weight: 500;
      font-size: 14px;
      color: #222222;
      text-shadow: 0px 1px 16px rgba(0, 212, 229, 0.24);
      text-align: center;
    }
  }
}

/* 健康指数图表 */
.health-chart {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.current-score {
  font-size: 14px;
  color: #666;
}
.chart-container {
  flex: 1;
}

.chart {
  width: 100%;
  height: 100%;
}

.health-tabs {
  min-height: 400px;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 20px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

/* 家庭成员切换样式 */
.family-member-tabs {
  display: flex;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 20px;
}

.family-member-tab {
  padding: 12px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  color: #606266;
  font-size: 14px;
  transition: all 0.3s;
}

.family-member-tab:hover {
  color: #409eff;
}

.family-member-tab.active {
  color: #409eff;
  border-bottom-color: #409eff;
  font-weight: 500;
}
</style>
